package baza.games.airSoccer;

import android.content.Context;
import android.graphics.Canvas;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class GameFieldView extends SurfaceView implements SurfaceHolder.Callback
{
	public class AirSoccerThread extends Thread {
		
		private SurfaceHolder surfaceHolder;
//		private Context context;
//		private Handler handler;
		public boolean isRunning;
	    private long sleepTime;
	    private long delay=10;
		private AirSoccerEngine engine;
		
		
		public AirSoccerThread(SurfaceHolder surfaceHolder, Context context,
			Handler handler) {
			this.surfaceHolder = surfaceHolder;
			//this.context = context;
			//this.handler = handler;
			this.isRunning = true;
		}
		
		public void generateComponents()
		{
			AirSoccerEngine.netHeight = getHeight();
			AirSoccerEngine.netWidth = getWidth();
			engine = new AirSoccerEngine();
		}
		
		@Override
		public void run(){
			generateComponents();
			while(this.isRunning) {
				
				long beforeTime = System.nanoTime();
				
				engine.processaInput();
				engine.update();
				Canvas c = null;
				
				
				try {
					c = surfaceHolder.lockCanvas(null);
					synchronized (surfaceHolder) {
						engine.doDraw(c);
					}
				} finally {
					// do this in a finally so that if an exception is thrown
					// during the above, we don't leave the Surface in an
					// inconsistent state
					if (c != null) {
						surfaceHolder.unlockCanvasAndPost(c);
					}
				}
				
				
				this.sleepTime = delay-((System.nanoTime()-beforeTime)/1000000L);

	            try {
	                if(sleepTime>0){
	                	sleep(sleepTime);
	                }
	            } catch (InterruptedException ex) {}
			}
		}

		public void doTouchEvent(MotionEvent event) {
			synchronized (surfaceHolder) 
			{
				if(this.isRunning)
				{
						engine.doTouch(event);
				}
			}
			
		}
		
	}
	
	private AirSoccerThread thread;


	public GameFieldView(Context context)
	{
		super(context);
		
		SurfaceHolder holder = getHolder();
		holder.addCallback(this);
		
		//generateComponents();
		
		thread = new AirSoccerThread(holder, context, new Handler());
		
	}
	
	public GameFieldView(Context context, AttributeSet attrs)
	{
		super(context, attrs);
		
		
		SurfaceHolder holder = getHolder();
		holder.addCallback(this);
		
		
		//generateComponents();
		
		thread = new AirSoccerThread(holder, context, new Handler());

	}
	
	public GameFieldView(Context context, AttributeSet attrs, int def)
	{
		super(context, attrs, def);
		
		SurfaceHolder holder = getHolder();
		holder.addCallback(this);
		
		//generateComponents();
		
		thread = new AirSoccerThread(holder, context, new Handler());
	}
	

	
	@Override
	public boolean onTouchEvent(MotionEvent event)
	{
		thread.doTouchEvent(event);
		//return super.onTouchEvent(event);
		return true;
	}
	
    //these methods are overridden from the SurfaceView super class. They are automatically called 
    //when a SurfaceView is created, resumed or suspended.
    public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {}

    public void surfaceDestroyed(SurfaceHolder arg0) {
        boolean retry = true;
        thread.isRunning = false;
        //code to end gameloop
        while (retry) {
            try {
                //code to kill Thread
                thread.join();
                retry = false;
            } catch (InterruptedException e) {
            }
        }

    }

    public void surfaceCreated(SurfaceHolder arg0) 
    {
        if(thread == null){
            //When game is opened again in the Android OS
            thread = new AirSoccerThread(getHolder(), getContext(), getHandler());
             thread.start();
        }else{
            //creating the game Thread for the first time
           thread.start();
        }
      }
    /*
    @Override
    public void onSizeChanged(int w, int h, int oldw, int oldh){
    	Log.d("Debug", String.valueOf(oldh));
    	AirSoccerEngine.netHeight = h;
    	AirSoccerEngine.netWidth = w;
    }*/
}